package com.petsdar.utils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA
 * User: heroC
 * Date: 2020/6/28
 * Time: 16:55
 * Description: 获取一个PassID，该PassID用于存储登录用户的临时身份
 * Version: V1.0
 */
public class PassID {

    /**
     * 生成最初的uuid数据，然后将username转换成字节数组，将字节数组中的元素
     * 将每个元素加上十进制数11后转换成16进制的数，追加到StringBuilder对象中，
     * 将StringBuilder字母都转成大写。如果长度大于8位，就截取前8位，然后将该8
     * 位数据中的所有数字替换成对应的字母。如果长度没有大于8位，直接将其中的数
     * 字替换位对应的字母。返回最终passID。
     * @param userName 用户名
     * @return
     */
    public static String getPassID(String userName){
        String uuidRandom = UUID.randomUUID().toString().replaceAll("-", "");
        String s = uuidRandom.toUpperCase();
        byte[] bytes = userName.getBytes();
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append(Integer.toHexString(aByte+11));
        }
        String userNameHex = sb.toString().toUpperCase();
        String code;
        if (userNameHex.length()>8){
            code = userNameHex.substring(0, 8);
            code = replace(s,code);
            return code;
        }else {
            code = userNameHex;
            code = replace(s, code);
            System.out.println(code);
            return code;
        }
    }

    /**
     * 将数字替换为对应的字母，返回替换后的数据参合uuid后的最终passID的结果
     * @param s uuid
     * @param resourceCode 未替换为字母的字符串
     * @return
     */
    private static String replace(String s, String resourceCode){
        String[] code = {"t","X","c","E","H","Z","a","i","p","W"};
        for (int i = 0; i < code.length; i++) {
            s=s.replaceAll(i+"",code[i]);
            resourceCode = resourceCode.replaceAll(i+"",code[i]);
        }
        return s+"++"+resourceCode;
    }
}
